package service

import (
	"FlowMaster/model"
	"fmt"
	"os"
	"strconv"
)

const (
	accessTokenEnvVar = "ACCESS_TOKEN"
	tokenTypeEnvVar   = "TOKEN_TYPE"
	expiresInEnvVar   = "EXPIRES_IN"
	scenicID          = "SCENICID"
)

func GetScenicIDFromEnv() (string, error) {
	scenicID := os.Getenv(scenicID)
	if scenicID == "" {
		return "", fmt.Errorf("缺少环境变量")
	}
	return scenicID, nil
}

func SetScenicID(scenicid string) error {
	err := os.Setenv(scenicID, scenicid)
	if err != nil {
		return err
	}
	return nil
}
func GetTokenFromEnv() (*model.TokenData, error) {
	accessToken := os.Getenv(accessTokenEnvVar)
	tokenType := os.Getenv(tokenTypeEnvVar)
	expiresIn := os.Getenv(expiresInEnvVar)

	if accessToken == "" || tokenType == "" || expiresIn == "" {
		return nil, fmt.Errorf("缺少环境变量")
	}
	ex, _ := strconv.Atoi(expiresIn)
	tokenData := &model.TokenData{
		Access_token: accessToken,
		Token_type:   tokenType,
		Expires_in:   int64(ex),
	}
	return tokenData, nil
}

func SetTokenToEnv(accessToken string, tokenType string, expiresIn string) error {
	lg.Debugf("SetTokenToEnv: %s %s %s", accessToken, tokenType, expiresIn)
	err := os.Setenv(accessTokenEnvVar, accessToken)
	if err != nil {
		return err
	}
	err = os.Setenv(tokenTypeEnvVar, tokenType)
	if err != nil {
		return err
	}
	err = os.Setenv(expiresInEnvVar, expiresIn)
	if err != nil {
		return err
	}
	return nil
}
